package database

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/brianvoe/sjwt"
	"time"
)

type User struct {
	Id       int
	UserName string `orm:"unique;size(255)" description:"用户名"`
	PassWord string `description:"密码"`
	Role     *Role  `orm:"rel(fk)" description:"角色信息"`
}

type Role struct {
	Id          int
	Name        string        `orm:"unique" description:"角色名"`
	Permissions []*Permission `orm:"reverse(many)" description:"权限信息"`
	Users       []*User       `orm:"reverse(many)" description:"用户"`
}

type Permission struct {
	Id    int
	Code  string  `orm:"unique" description:"权限唯一标识符"`
	Name  string  `description:"权限名称"`
	Roles []*Role `orm:"rel(m2m)" description:"角色"`
}

func (self *User) Token() string {
	token := sjwt.New()
	token.Set("id", self.Id)
	token.SetExpiresAt(time.Now().Add(time.Hour * 12))
	o := orm.NewOrm()
	var permission []orm.Params;
	o.QueryTable("permission").Filter("Roles__role__id", self.Role.Id).Values(&permission, "Code", "Name")
	token.Set("permission", permission)
	return token.Generate([]byte("fadsffdsafsdf"))
}

func (self *User) CheckPassWord(password string) bool {
	return self.PassWord == password
}

func FilterOneUserByName(UserName string) (*User, error) {
	fmt.Println(UserName)
	user := &User{UserName: UserName}
	o := orm.NewOrm()
	error := o.QueryTable("user").Filter("user_name", UserName).One(user)
	if error != nil {
		return nil, error
	}
	return user, error
}

func RegisterUser(username string, password string) (*User, error) {
	user := &User{
		UserName: username,
		PassWord: password,
	}
	o := orm.NewOrm()
	_, error := o.Insert(user)
	if error != nil {
		return nil, error
	}
	return user, nil
}



func AddRole()  {
	
}

func init() {
	orm.RegisterModel(new(User))
	orm.RegisterModel(new(Permission))
	orm.RegisterModel(new(Role))
}
